import { create } from 'zustand'
import type { Order } from '../types/api'

interface OrderState {
  orders: Order[]
  currentOrder: Order | null
  loading: boolean
}

interface OrderActions {
  setOrders: (orders: Order[]) => void
  addOrder: (order: Order) => void
  updateOrder: (orderId: string, updates: Partial<Order>) => void
  setCurrentOrder: (order: Order | null) => void
  setLoading: (loading: boolean) => void
  clearOrders: () => void
}

export const useOrderStore = create<OrderState & OrderActions>((set, get) => ({
  orders: [],
  currentOrder: null,
  loading: false,

  setOrders: (orders) => set({ orders }),

  addOrder: (order) => set((state) => ({
    orders: [order, ...state.orders]
  })),

  updateOrder: (orderId, updates) => set((state) => ({
    orders: state.orders.map(order => 
      order.id === orderId ? { ...order, ...updates } : order
    ),
    currentOrder: state.currentOrder?.id === orderId 
      ? { ...state.currentOrder, ...updates } 
      : state.currentOrder
  })),

  setCurrentOrder: (order) => set({ currentOrder: order }),

  setLoading: (loading) => set({ loading }),

  clearOrders: () => set({
    orders: [],
    currentOrder: null,
    loading: false
  })
}))

export default useOrderStore